using Microsoft.EntityFrameworkCore;
using RiceShop.Models;

namespace RiceShop.Services
{
    /// <summary>
    /// 地址管理服务接口
    /// </summary>
    public interface IAddressService
    {
        Task<List<Address>> GetAddressListAsync(long userId);
        Task<Address> GetAddressByIdAsync(long userId, long addressId);
        Task<Address> CreateAddressAsync(long userId, Address address);
        Task<Address> UpdateAddressAsync(long userId, long addressId, Address address);
        Task DeleteAddressAsync(long userId, long addressId);
        Task<Address> SetDefaultAddressAsync(long userId, long addressId);
        Task<Address?> GetDefaultAddressAsync(long userId);
    }

    /// <summary>
    /// 地址管理服务实现类
    /// 提供用户收货地址的增删改查等管理功能
    /// </summary>
    public class AddressService : IAddressService
    {
        private readonly ApplicationDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public AddressService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取用户的地址列表
        /// </summary>
        public async Task<List<Address>> GetAddressListAsync(long userId)
        {
            return await _context.Addresses
                .Where(a => a.UserId == userId)
                .OrderByDescending(a => a.IsDefault)
                .ThenByDescending(a => a.Id)
                .ToListAsync();
        }

        /// <summary>
        /// 获取指定地址信息
        /// </summary>
        public async Task<Address> GetAddressByIdAsync(long userId, long addressId)
        {
            var address = await _context.Addresses
                .FirstOrDefaultAsync(a => a.Id == addressId && a.UserId == userId);

            if (address == null)
            {
                throw new KeyNotFoundException("地址不存在");
            }

            return address;
        }

        /// <summary>
        /// 创建新地址
        /// </summary>
        public async Task<Address> CreateAddressAsync(long userId, Address address)
        {
            // 检查是否是第一个地址
            var isFirstAddress = !await _context.Addresses
                .AnyAsync(a => a.UserId == userId);

            // 如果是第一个地址或指定为默认地址
            if (isFirstAddress || address.IsDefault)
            {
                await ClearDefaultAddressAsync(userId);
                address.IsDefault = true;
            }

            address.UserId = userId;
            _context.Addresses.Add(address);
            await _context.SaveChangesAsync();
            return address;
        }

        /// <summary>
        /// 更新地址信息
        /// </summary>
        public async Task<Address> UpdateAddressAsync(long userId, long addressId, Address addressUpdate)
        {
            var address = await _context.Addresses
                .FirstOrDefaultAsync(a => a.Id == addressId && a.UserId == userId);

            if (address == null)
            {
                throw new KeyNotFoundException("地址不存在");
            }

            if (addressUpdate.IsDefault && !address.IsDefault)
            {
                await ClearDefaultAddressAsync(userId);
            }

            // 更新地址信息
            address.ReceiverName = addressUpdate.ReceiverName;
            address.PhoneNumber = addressUpdate.PhoneNumber;
            address.Province = addressUpdate.Province;
            address.City = addressUpdate.City;
            address.District = addressUpdate.District;
            address.DetailAddress = addressUpdate.DetailAddress;
            address.IsDefault = addressUpdate.IsDefault;

            await _context.SaveChangesAsync();
            return address;
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        public async Task DeleteAddressAsync(long userId, long addressId)
        {
            var address = await _context.Addresses
                .FirstOrDefaultAsync(a => a.Id == addressId && a.UserId == userId);

            if (address == null)
            {
                throw new KeyNotFoundException("地址不存在");
            }

            _context.Addresses.Remove(address);
            await _context.SaveChangesAsync();

            // 如果删除的是默认地址，则将最新的地址设为默认
            if (address.IsDefault)
            {
                var newDefaultAddress = await _context.Addresses
                    .Where(a => a.UserId == userId)
                    .OrderByDescending(a => a.Id)
                    .FirstOrDefaultAsync();

                if (newDefaultAddress != null)
                {
                    newDefaultAddress.IsDefault = true;
                    await _context.SaveChangesAsync();
                }
            }
        }

        /// <summary>
        /// 设置默认地址
        /// </summary>
        public async Task<Address> SetDefaultAddressAsync(long userId, long addressId)
        {
            var address = await _context.Addresses
                .FirstOrDefaultAsync(a => a.Id == addressId && a.UserId == userId);

            if (address == null)
            {
                throw new KeyNotFoundException("地址不存在");
            }

            await ClearDefaultAddressAsync(userId);
            address.IsDefault = true;
            await _context.SaveChangesAsync();
            return address;
        }

        /// <summary>
        /// 清除用户的默认地址
        /// </summary>
        private async Task ClearDefaultAddressAsync(long userId)
        {
            var defaultAddress = await _context.Addresses
                .FirstOrDefaultAsync(a => a.UserId == userId && a.IsDefault);

            if (defaultAddress != null)
            {
                defaultAddress.IsDefault = false;
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 获取用户的默认收货地址
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>默认地址，如果没有则返回null</returns>
        public async Task<Address?> GetDefaultAddressAsync(long userId)
        {
            // 首先尝试获取默认地址
            var defaultAddress = await _context.Addresses
                .FirstOrDefaultAsync(a => a.UserId == userId && a.IsDefault);

            // 如果没有默认地址，则返回最新添加的地址
            if (defaultAddress == null)
            {
                defaultAddress = await _context.Addresses
                    .Where(a => a.UserId == userId)
                    .OrderByDescending(a => a.Id)
                    .FirstOrDefaultAsync();
            }

            return defaultAddress;
        }
    }
}